<?php

namespace app\common\library;

use think\Config;
use think\Log;

class Wechat
{
    protected $appid;
    protected $secret;
    
    public function __construct()
    {
        $this->appid = Config::get('wechat.app_id');
        $this->secret = Config::get('wechat.secret');
    }

    /**
     * 获取微信用户信息
     * @param string $code
     * @return array|false
     */
    public function getUserInfo($code)
    {
        try {
            // 获取access_token
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token";
            $params = [
                'appid' => $this->appid,
                'secret' => $this->secret,
                'code' => $code,
                'grant_type' => 'authorization_code'
            ];
            
            $response = $this->httpGet($url, $params);
            $result = json_decode($response, true);
            
            if (!isset($result['access_token'])) {
                Log::error('获取微信access_token请求参数：' . json_encode($params));
                Log::error('获取微信access_token失败：' . $response);
                return false;
            }

            // 获取用户信息
            $url = "https://api.weixin.qq.com/sns/userinfo";
            $params = [
                'access_token' => $result['access_token'],
                'openid' => $result['openid'],
                'lang' => 'zh_CN'
            ];
            
            $response = $this->httpGet($url, $params);
            $userInfo = json_decode($response, true);
            
            if (!isset($userInfo['openid'])) {
                Log::error('获取微信用户信息失败：' . $response);
                return false;
            }
            
            return $userInfo;
        } catch (\Exception $e) {
            Log::error('微信授权异常：' . $e->getMessage());
            return false;
        }
    }

    /**
     * 发送GET请求
     * @param string $url
     * @param array $params
     * @return string
     */
    protected function httpGet($url, $params = [])
    {
        if ($params) {
            $url .= '?' . http_build_query($params);
        }
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }
}